package xyz.labmem.lipx.core.tool

import cn.hutool.core.date.DateUtil
import cn.hutool.core.thread.ExecutorBuilder
import cn.hutool.log.StaticLog
import xyz.labmem.lipx.core.entity.ClientConfig
import java.util.*
import java.util.concurrent.ExecutorService


/**
 * @description: do something
 * @author: ltty
 * @date: 2022/6/15 17:25
 */
class LogInfo {

    companion object {

        var debug = false

        val logs = LinkedList<String>()

        private val executor: ExecutorService = ExecutorBuilder.create()
            .setCorePoolSize(1)
            .setMaxPoolSize(1)
            .setKeepAliveTime(0)
            .build()

        fun appendLog(msg: String) {
            addTask("${DateUtil.now()} 【INFO】 $msg\n")
        }

        fun appendLogError(msg: String) {
            addTask("${DateUtil.now()} 【ERROR】 $msg\n")
            System.gc()
        }

        fun appendLog(msg: String, config: ClientConfig) {
            addTask("${DateUtil.now()} 【INFO】(${config.remark})【${config.serverHost}:${config.serverPort}->${config.targetPort}】 $msg\n")
        }

        fun appendLogError(msg: String, config: ClientConfig) {
            addTask("${DateUtil.now()} 【ERROR】(${config.remark})【${config.serverHost}:${config.serverPort}->${config.targetPort}】 $msg\n")
            System.gc()
        }

        private fun addTask(msg: String) {
            executor.submit {
                if (logs.size > 1000)
                    logs.removeFirst()
                logs.add(msg)
                if (debug)
                    StaticLog.debug(msg)
                Thread.sleep(200)
            }
        }
    }
}